import React, { Component } from "react";
import empty from "../../assets/images/empty.png";
import "./Cart.scss";
import { Modal, Checkbox, TabBar, Icon, NavBar, Toast } from "antd-mobile";
import axios from "../../utils/myaxios";
const alert = Modal.alert;
class Cart extends Component {
  constructor(props) {
    super(props);
    this.contentRef = React.createRef();
  }
  state = {
    // TabBar部分状态
    selectedTab: 'redTab',
    hidden: false,
    fullScreen: false,
    //导航栏右侧图标是否被点击
    isSelect: false,
    mayLikeList: [],//返回推荐的数据
    backTop: false,//返回顶部栏默认隐藏
    AllCheck: false, //全选
    TotalMoney: 0.00,//总价
    GoodsNum: 0,//总数
    carts: [], //购物车数据
    words: "限时购",
  };
  // 推荐喜欢
  getMayLikeList = (res) => {
    this.setState({
      mayLikeList: res.data
    })
  }
  // 生命周期
  componentDidMount() {
    axios.get("/cart.php?action=cart_ad_and_recommend&productIds=&img_size=h").then(res => {
      // console.log(res);
      this.getMayLikeList(res)
    }).catch(err => {
      console.log(err);
    })
    // 注册滚动监听事件
    this.contentRef.current.parentElement.addEventListener("scroll", this.handleScroll);
    // // 获取本地缓存中的购物车数据
    let carts_str = localStorage.getItem("carts");
    let carts = JSON.parse(carts_str || "[]");
    // console.log(carts);
    this.saveCarts(carts);
  }
  // 保存小车
  saveCarts = (carts) => {
    this.carts = carts;
    localStorage.setItem("carts", JSON.stringify(carts));
    this.setState({
      carts,
    });
    this.handeAllCheck();
    this.handelTotal();
  };
  // 滚动事件
  handleScroll = () => {
    let parentElement = this.contentRef.current.parentElement;
    // let clientHeight = parentElement.clientHeight;    // 客户端高度
    // let scrollHeight = parentElement.scrollHeight;    // 列表的高度
    let scrollTop = parentElement.scrollTop;    // 列表已经滚动的高度
    if (scrollTop > 1000) {
      this.setState({
        backTop: true,
      })
    } else {
      this.setState({
        backTop: false,
      })
    }
  }
  // 处理单选框变化
  handleChekChange = (index) => {
    let carts = this.state.carts;
    carts[index].checked = !carts[index].checked; //!true
    this.saveCarts(carts);
    console.log(carts);
  };
  // 处理多选框变化
  handleAllChekChange = () => {
    let carts = this.carts;
    let AllCheck = !this.state.AllCheck;
    //循环单选框框
    // console.log(this.state.carts);
    this.state.carts.forEach((v) => {
      v.checked = AllCheck;
    });
    this.setState({
      AllCheck,
    });
    this.saveCarts(carts);
  };
  // 检查是否全选
  handeAllCheck = (e) => {
    // e.preventDefault();
    // 判断 全选按钮的状态
    let AllCheck = true;
    let bool = this.state.carts.some((v) => {
      // 只要有一个是假
      return !v.checked ? true : false;
    });
    if (bool) {
      AllCheck = false; // 真的情况
    }
    this.setState({
      AllCheck: AllCheck,
    });
  };
  // 合计及总价
  handelTotal = () => {
    let carts = this.state.carts;
    let TotalMoney = 0;
    let GoodsNum = 0;
    carts.forEach(v => {
      if (v.checked) {
        TotalMoney += v.price * v.num;
        GoodsNum += v.num;
      }
    })
    this.setState({
      TotalMoney,
      GoodsNum,
    });
  }
  // num+
  handleAdd = (index) => {
    let carts = this.carts;
    carts[index].num++;
    this.saveCarts(carts);
  };
  // num-
  handleSub = (index) => {
    let carts = this.carts;
    if (carts[index].num - 1 === 0) {
      // 提示用户
      // 再减少就要删除商品
      alert("删除商品", "您确认要删除商品吗???", [
        { text: "取消", onPress: () => console.log("删除商品取消") },
        {
          text: "确定",
          onPress: () => {
            // 删除商品
            carts.splice(index, 1);
            // 保存修改商品的信息
            this.saveCarts(carts);
            Toast.info("删除成功!", 1)
            // Toast.hide();
          },
        },
      ]);
    } else {
      --carts[index].num;
      this.saveCarts(carts);
    }
  };
  // 删除商品
  handleDel = (index) => {
    let carts = this.carts;
    alert("删除商品", "您确认要删除商品吗???", [
      { text: "取消", onPress: () => console.log("删除商品取消") },
      {
        text: "确定",
        onPress: () => {
          // 删除商品
          carts.splice(index, 1);
          // 保存修改商品的信息
          this.saveCarts(carts);
          Toast.info("删除成功!", 1)
          // Toast.hide();
        },
      },
    ]);
  }
  // 编辑
  handelCompile = (index) => {
    let carts = this.state.carts;
    carts[index].compile = !carts[index].compile
    this.saveCarts(carts);
  }
  // 组件卸载
  componentWillUnmount() {
    // 卸载监听事件
    this.contentRef.current.parentElement.removeEventListener("scroll", this.handleScroll);
  }
  // 显示tabbar
  tabbarBlockClick = () => {
    this.setState({
      isSelect: !this.state.isSelect,
    })
  }
  // 逛一逛
  handleBackHome = () => {
    this.props.history.push("index")
  }
  // 我的收藏
  handleBackCollect=()=>{
    this.props.history.push("collect")
  }
  // 回到顶部
  backToTop = () => {
    let scrollTop = this.contentRef.current.parentElement.scrollTop;
    let myTimer = setInterval(() => {
      scrollTop -= 200;
      if (scrollTop <= 0) {
        scrollTop = 0;
        window.clearInterval(myTimer);
      }
      this.contentRef.current.parentElement.scrollTo(0, scrollTop);
    }, 10)
  }
  // 功能阉割
  nouseClick = (params) => {
    alert("功能阉割", "这是一个重新选择商品规格的功能，由于获取不到数据，只能阉割。(*￣︶￣)", [
      { text: "取消", onPress: () => console.log("阉割取消") },
      { text: "确定", onPress: () => console.log("阉割成功") },
    ]);
  }

  // 跳转到详情页
  goodDetailClick = (goods_info) => {
    this.props.history.push({ pathname: "/goodDetail", state: { goods_info: goods_info } });
  }
  // 跳转到支付页面
  gotoPay = (params) => {
    this.props.history.push("/pay/0");
  }
  render() {
    return (
      <div className="dd-cart">
        {/* 商品列表导航条开始 */}
        <NavBar
          mode="light"
          className="dd-cart-nav"
          icon={<Icon type="left" />}
          onLeftClick={() => window.history.go(-1)}
          rightContent={[
            <i className={this.state.isSelect === false ? "iconfont icon-19" : "iconfont icon-cha"} onClick={this.tabbarBlockClick} key={123}></i>
          ]}
        >购物车</NavBar>
        {/* 商品列表导航条结束 */}
        {/* 商品列表tabbar开始 */}
        <div className={this.state.isSelect === false ? "dd-cart-tabbar" : "active dd-cart-tabbar"}>
          <TabBar
            // 未选中的字体颜色
            unselectedTintColor="#949494"
            // tintColor
            tintColor="#ff2d4a"
            // tabbar 背景色
            barTintColor="#eeeeee"
            hidden={this.state.hidden}
            tabBarPosition="top"
          >
            <TabBar.Item
              title="首页"
              key="index"
              // 默认展示图片
              icon={<i className="iconfont icon-main"></i>}
              // 选中后的展示图片
              selectedIcon={
                <i
                  className="iconfont icon-main"
                  style={{ color: "#ff2d4a" }}
                ></i>
              }
              selected={this.props.location.pathname === "/"}
              onPress={() => {
                this.props.history.push("/");
              }}
            >
              {this.props.location.pathname === "/" && this.props.children}
            </TabBar.Item>
            <TabBar.Item
              title="分类"
              key="category"
              icon={<i className="iconfont icon-fenleichazhao"></i>}
              selectedIcon={
                <i
                  className="iconfont icon-fenleichazhao"
                  style={{ color: "#ff2d4a" }}
                ></i>
              }
              selected={this.props.location.pathname === "/category"}
              onPress={() => {
                this.props.history.push("/category");
              }}
            >
              {this.props.location.pathname === "/category" &&
                this.props.children}
            </TabBar.Item>
            <TabBar.Item
              title="值得买"
              key="worthBuy"
              icon={<i className="iconfont icon-gouwudai"></i>}
              selectedIcon={
                <i
                  className="iconfont icon-gouwudai"
                  style={{ color: "#ff2d4a" }}
                ></i>
              }
              selected={this.props.location.pathname === "/worthBuy"}
              onPress={() => {
                this.props.history.push("/worthBuy");
              }}
            >
              {this.props.location.pathname === "/worthBuy" &&
                this.props.children}
            </TabBar.Item>
            <TabBar.Item
              title="购物车"
              key="cart"
              icon={<i className="iconfont icon-gouwuche1"></i>}
              selectedIcon={
                <i
                  className="iconfont icon-gouwuche1"
                  style={({ color: "#ff2d4a", fontSize: "20px" })}
                ></i>
              }
              selected={this.props.location.pathname === "/cart"}
              onPress={() => {
                this.props.history.push("/cart");
              }}
            >
              {this.props.location.pathname === "/cart" && this.props.children}
            </TabBar.Item>
            <TabBar.Item
              title="我的"
              key="my"
              icon={<i className="iconfont icon-wode"></i>}
              selectedIcon={
                <i
                  className="iconfont icon-wode"
                  style={{ color: "#ff2d4a" }}
                ></i>
              }
              selected={this.props.location.pathname === "/my"}
              onPress={() => {
                this.props.history.push("/my");
              }}
            >
              {this.props.location.pathname === "/my" && this.props.children}
            </TabBar.Item>
          </TabBar>
          {/* <Tabbar className="cart-tabbar-content"></Tabbar> */}
        </div>
        {/* 商品列表tabbar开始 */}
        {/* 购物车内容开始 */}
        <div className="dd-cart-content" >
          {
            this.state.carts && this.state.carts.length ? (
              <div>
                <div className="cart-goods">
                  {
                    this.state.carts.map((v, i) => {
                      return (
                        <div className="cart-goods-list" key={v.id || v.product_id}>
                          {
                            !v.compile ? (
                              <div>
                                {/* 店铺title开始 */}
                                <div className="list-shop-title">
                                  <Checkbox
                                    onChange={this.handleChekChange.bind(this, i)}
                                    checked={v.checked}
                                  ></Checkbox>
                                  <i className="iconfont icon-dangdangwang"></i>
                                  <p>{v.shop_name || v.product_id}</p>
                                  <span onClick={this.handelCompile.bind(this, i)}>编辑</span>
                                </div>
                                {/* 店铺title结束 */}
                                {/* 商品内容开始 */}
                                <div className="cart-goods-content">
                                  <div className="content-left">
                                    <Checkbox
                                      onChange={this.handleChekChange.bind(this, i)}
                                      checked={v.checked}
                                    ></Checkbox>
                                  </div>
                                  <div className="content-mid">
                                    <img src={v.image_url} alt="" />
                                  </div>
                                  <div className="content-right">
                                    <p>{v.name}</p>
                                    <em>
                                      <i className="money-left">￥</i>
                                      <i className="money-right">{v.price}</i>
                                    </em>
                                    <span className="flag">{v.promo_flag || v.label_type || this.state.words}</span>
                                    <div className="content-right-bottom">
                                      <span className="goodsNum"> X{v.num}</span>
                                      <i className="iconfont icon-bianji" onClick={this.nouseClick}></i>
                                    </div>
                                  </div>
                                </div>
                                {/* 商品内容结束 */}
                              </div>
                            ) : (
                                <div>
                                  {/* 店铺title开始 */}
                                  <div className="list-shop-title">
                                    <i className="iconfont icon-yuanquan"></i>
                                    <i className="iconfont icon-dangdangwang"></i>
                                    <p>{v.author_name}</p>
                                    <span onClick={this.handelCompile.bind(this, i)}>完成</span>
                                  </div>
                                  {/* 店铺title结束 */}
                                  {/* 店铺内容编辑开始 */}
                                  <div className="edit-goods-content">
                                    <div className="edit-left">
                                      <img src={v.image_url} alt="" />
                                    </div>
                                    <div className="edit-right">
                                      <div className="caclNum">
                                        <i className="iconfont icon-iconjian" onClick={this.handleSub.bind(this, i)}></i>
                                        <div className="num">{v.num}</div>
                                        <i className="iconfont icon-jia" onClick={this.handleAdd.bind(this, i)}></i>
                                      </div>
                                      <div className="del" onClick={this.handleDel.bind(this, i)}>
                                        删除
                                    </div>
                                    </div>

                                  </div>
                                  {/* 店铺内容编辑结束*/}
                                </div>
                              )
                          }
                        </div>
                      )
                    })
                  }
                </div>
                <div className="cart-goods-total">
                  <div className="total-left">
                    <Checkbox
                      onClick={this.handleAllChekChange}
                      checked={this.state.AllCheck}
                    ></Checkbox>
                    <span className="quanxuan">全选</span>
                  </div>
                  <div className="total-mid">
                    <span className="sum">合计</span>
                    <em>
                      <i>￥</i>
                      <i>{this.state.TotalMoney.toFixed(2)}</i>
                    </em>
                  </div>
                  <div className="total-right">
                    {
                      !this.state.GoodsNum && this.state.carts.length ? (<span className="text5">去结算({this.state.GoodsNum})</span>
                      ) : (
                          <span className="text3" onClick={this.gotoPay}>去结算({this.state.GoodsNum})</span>
                        )
                    }
                    {/* 结算({this.state.GoodsNum}) */}
                  </div>
                </div>
              </div>
            ) : (
                <div className="cart-empty">
                  <img src={empty} alt="" />
                  <p>您还没有购买任何商品</p>
                  <div className="cart-introduce">
                    <div className="introduce-left" onClick={this.handleBackHome}>逛一逛</div>
                    <div className="introduce-right"  onClick={this.handleBackCollect}>我的收藏</div>
                  </div>
                </div>
              )
          }
          {/* 可能喜欢开始 */}
          <div className="cart-maylike">
            {/* 可能喜欢开始 */}
            <h2 className="maylike-title">
              ——
            <em>
                <i className="iconfont icon-icon-test-copy "></i>
                <b>根据您的偏好猜您可能喜欢</b>
              </em>
            ——
          </h2>
            {/* 可能喜欢结束 */}
            {/* 推荐商品开始 */}
            <ul className="maylike-content">
              {
                this.state.mayLikeList.map(v => {
                  return (
                    <li className="content-list" key={v.product_id} onClick={this.goodDetailClick.bind(this, v)}>
                      <img src={v.image_url} alt="" />
                      <span className="name">{v.name}</span>
                      <div className="content-list-title">
                        {
                          v.product_tags.map(vv => {
                            return (
                              <div className="label" key={vv.name}>{vv.name}</div>
                            )
                          })
                        }
                      </div>
                      <em className="money">
                        <i className="left">￥</i>
                        <i className="right">{v.price}</i>
                      </em>
                      <span className="detail">{v.review_count}人评价</span>
                    </li>
                  )
                })
              }
            </ul>
            {/* 推荐商品结束 */}
          </div>
          {/* 可能喜欢结束 */}
          {/* 回到顶部开始 */}
          <div className={this.state.backTop === false ? "cart-fixed-box-none" : "cart-fixed-box-block"} onClick={this.backToTop} ref={this.contentRef}>
            <i className="iconfont icon-dingbu"></i>
          </div>
          {/* 回到顶部结束 */}
        </div>
        {/* 购物车内容结束 */}

      </div >
    );
  }
}

export default Cart;
